package com.mrdeer.iot.handler;

import com.mrdeer.iot.bean.command.Protocol;
import com.mrdeer.iot.utils.ByteUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 自定义协议数据解析
 */
@Slf4j
public class ProtocolEncoderHandler extends MessageToByteEncoder<Protocol> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Protocol msg, ByteBuf out) throws Exception {
        //写入消息Protocol具体内容
        out.writeByte(ByteUtils.hexToByte(msg.getHeader()));
        out.writeByte(ByteUtils.hexToByte(msg.getCode()));
        out.writeByte(ByteUtils.hexToByte(msg.getVersion()));
        out.writeByte(ByteUtils.hexToByte(msg.getLength()));
        out.writeBytes(ByteUtils.hex2byte(msg.getDest()));
        out.writeByte(ByteUtils.hexToByte(msg.getType()));
        out.writeBytes(ByteUtils.hex2byte(msg.getData()));
        out.writeBytes(ByteUtils.hex2byte(msg.getCrc()));
    }
}
